<template>
    <div>
        <el-button type="primary" icon="el-icon-circle-plus-outline" round style="margin: 10px 2%"
            @click="showAddOrEdit">添加</el-button>
        <!-- 表格，显示数据 -->
        <el-table :data="tableData" border stripe style="margin-left:1%; width: 98%; text-align: center;">
            <el-table-column type="index" label="序号" width="80px" align="center">
            </el-table-column>
            <el-table-column prop="tmName" label="品牌名称" align="center">
            </el-table-column>
            <el-table-column label="品牌LOGO">
                <template slot-scope="{ row, $index }">
                    <img :src="row.logoUrl" alt="" style="width: auto; height: 100px" />
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="{ row, $index }">
                    <el-button round type="warning" icon="el-icon-edit" @click="showAddOrEdit(row)">修改</el-button>
                    <el-button round type="danger" icon="el-icon-delete" @click="deleteInfo(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[3, 5, 15]" :page-size="pageSize" layout="prev, pager, next, jumper,->,sizes,total"
            :total="total" :pager-count="7" style="margin-top: 20px; text-align: center;">
        </el-pagination>

        <!-- 对话框-弹窗 -->
        <el-dialog :title="brandform.id ? '修改品牌' : '添加品牌'" :visible.sync="dialogFormVisible">
            <el-form :model="brandform" style="width: 80%" :rules="myRules" ref="brandformRef">
                <el-form-item prop="tmName" label="品牌名称:" label-width="120px">
                    <el-input v-model="brandform.tmName"></el-input>
                </el-form-item>
                <el-form-item label="品牌LOGO:" label-width="120px" prop="logoUrl">
                    <el-upload class="avatar-uploader" action="/dev-api/admin/product/fileUpload"
                        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="brandform.logoUrl" :src="brandform.logoUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过2MB</div>
                    </el-upload>

                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveInfo">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { valid } from 'mockjs';

export default {
    name: 'BrandManager',
    data() {
        var checktmNameLength = (rule, value, callback) => {
            if (value.length < 2 || value.length > 10) {
                callback(new Error("品牌名称2-10位"));
            } else {
                callback();
            }
        }
        return {
            tableData: [],
            currentPage: 1,
            pageSize: 3,
            total: 0,
            totalPage: 0,
            dialogFormVisible: false, // 当为true时弹窗
            brandform: {
                tmName: '',
                logoUrl: '',

            },
            myRules: { //表单验证
                tmName: [
                    { required: true, message: '请输入品牌名称', trigger: 'blur' },
                    { validator: checktmNameLength, trigger: 'change' }//自定义验证规则

                ],
                logoUrl: [
                    { required: true, message: '必须上传Logo', trigger: 'blur' }

                ],
            },
        }

    },
    methods: {
        //获取列表数据
        async getGoodsList() {
            const result = await this.$API.brand.reqBrandList(this.currentPage, this.pageSize);
            if (result.code == 200) {
                this.tableData = result.data.records;
                this.total = result.data.total;
                this.totalPage = result.data.pages;
            }

        },
        //添加或修改
        showAddOrEdit(val) {
            this.dialogFormVisible = true;
            this.brandform = { tmName: '', logoUrl: '' }
            if (val.id) this.brandform = { ...val };
        },
        //删除
        deleteInfo(val) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const result = await this.$API.brand.reqDeleteBrand(val.id);
                if (result.code == 200) {
                    this.$message({ type: 'success', message: '删除成功!' });
                    if (this.tableData.length <= 1) this.currentPage = this.currentPage - 1;
                    this.getGoodsList();
                } else {
                    this.$message.error("删除失败！！，请联系管理员")
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //保存
        async saveInfo() {
            this.$refs.brandformRef.validate(async valid => {
                if (!valid) {
                    return false;
                }
                this.dialogFormVisible = false;
                const result = await this.$API.brand.reqAddOrUpdateBrand(this.brandform);
                if (result.code == 200) {
                    this.$message({
                        message: this.brandform.id ? '修改品牌成功' : '添加品牌成功',
                        type: 'success'
                    });
                    if (!this.brandform.id) {
                        this.currentPage = this.tableData.length < this.pageSize ? this.totalPage : this.totalPage + 1;
                    }
                    this.getGoodsList();
                } else {
                    this.$message.error(this.brandform.id ? '修改品牌失败' : '添加品牌失败');
                }
            })
        },


        //分页当PageSize改变时
        handleSizeChange(val) {
            this.pageSize = val;
            this.getGoodsList();
        },
        //当前页改变时
        handleCurrentChange(val) {
            this.currentPage = val;
            this.getGoodsList();
        },
        //上传图片处理，返回图片的地址
        handleAvatarSuccess(res, file) {
            this.brandform.logoUrl = res.data;
        },
        //上传图片对数据验证
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },




    },
    mounted() {
        this.getGoodsList();
    }
}
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>